/**
* <p>Title: WebDriverUtil.java</p>
* <p>Description: webdriver utils</p>
* <p>Company: www.huoyunren.com</p>
* @author duanxiangyun
* @date 2015年1月7日
* @version 1.0
*/
package com.hxbd.test.utils.webdriver;

import java.awt.Toolkit;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Arrays;
import java.util.concurrent.TimeUnit;

import org.apache.log4j.Logger;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebDriverException;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.ie.InternetExplorerDriver;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.openqa.selenium.remote.RemoteWebDriver;
import org.openqa.selenium.support.events.EventFiringWebDriver;
import org.openqa.selenium.support.events.WebDriverEventListener;


/**
 * webdriver初始化公共类:包括是否采用remote方式
 */
public class WebDriverUtil
{
	static WebDriver driver;
	private static Logger log = Logger.getLogger(WebDriverUtil.class);
//	private static String remote_add = "remote_add";
//	private static String remoteAdd = PageElementHandler.getStoreSettingPageProperties().getProperty(remote_add );
//	private static String RemoteUrl = "http://" + remoteAdd + "/wd/hub";
//	private static String testTools_add = "testTools_add";
//	private static String chromedriver = CommonUtils.getFilePath(PageElementHandler.getStoreSettingPageProperties().getProperty(testTools_add)) + "chromedriver.exe";
//	private static String IEDriver = CommonUtils.getFilePath(PageElementHandler.getStoreSettingPageProperties().getProperty(testTools_add)) + "IEDriverServer.exe";
	/**
	 * 打开Firefox浏览器
	 * @return WebDriver
	 */
	public static WebDriver getFireFoxDriver() {
		driver = new FirefoxDriver();
		driver.manage().window().maximize();
//		maximise(driver);
		driver.manage().timeouts().pageLoadTimeout(60, TimeUnit.SECONDS); // 设置页面加载超时的最大时长
		return driver;
	}
	
	/**
	 * remote方式打开Firefox浏览器
	 * @param nodeUrl 远程连接地址
	 * @return WebDriver
	 * @throws MalformedURLException
	 */
	public static WebDriver getRemoteFireFoxDriver(String nodeUrl) throws MalformedURLException {
		DesiredCapabilities dc = DesiredCapabilities.firefox(); // 设置需要驱动的浏览器，其他的浏览器都是以此类推
		driver = new RemoteWebDriver(new URL("http://" + nodeUrl + "/wd/hub"), dc);
		// 这个URL：localhost是要remote PC 的IPAddress，需要改为你自己的
		driver.manage().window().maximize();
//		maximise(driver);
		driver.manage().timeouts().pageLoadTimeout(60, TimeUnit.SECONDS); // 设置页面加载超时的最大时长
		return driver;
	}
	/**
	 * 打开IE浏览器
	 * @param IEDriverPath IEdriver存放路径
	 * @return Webdriver
	 */
	public static WebDriver getIEDriver(String IEDriverPath) {
		System.setProperty("webdriver.ie.driver",IEDriverPath);
	    DesiredCapabilities ieCapabilities = DesiredCapabilities.internetExplorer();
	    ieCapabilities.setCapability(
	    		InternetExplorerDriver.INTRODUCE_FLAKINESS_BY_IGNORING_SECURITY_DOMAINS,true);
		driver = new InternetExplorerDriver();
		driver.manage().window().maximize();
//		maximise(driver);
		driver.manage().timeouts().pageLoadTimeout(60, TimeUnit.SECONDS);
		return driver;
	}
	
	/**
	 * remote打开IE浏览器
	 * @param nodeUrl 远程连接地址
	 * @param IEDriverPath IEdriver存放路径
	 * @return webdriver
	 * @throws MalformedURLException
	 */
	public static WebDriver getRemoteIEDriver(String nodeUrl,String IEDriverPath) throws MalformedURLException {
		System.setProperty("webdriver.ie.driver",IEDriverPath);
	    DesiredCapabilities ieCapabilities = DesiredCapabilities.internetExplorer();
	    ieCapabilities.setCapability(
	    		InternetExplorerDriver.INTRODUCE_FLAKINESS_BY_IGNORING_SECURITY_DOMAINS,true);
		driver = new RemoteWebDriver(new URL("http://" + nodeUrl + "/wd/hub"), ieCapabilities);
		driver.manage().window().maximize();
//		maximise(driver);
		driver.manage().timeouts().pageLoadTimeout(60, TimeUnit.SECONDS);
		return driver;
	}
	/**
	 * 打开chrome浏览器
	 * @param chromeDriverPath chromedriver存放路径
	 * @return webdriver
	 */
	public static WebDriver getChromeDriver(String chromeDriverPath) {
		System.setProperty("webdriver.chrome.driver",chromeDriverPath);
		DesiredCapabilities capabilities = DesiredCapabilities.chrome();  
        capabilities.setCapability("chrome.switches", Arrays.asList("--incognito"));  
        ChromeOptions options = new ChromeOptions();  
        options.addArguments("--test-type");  
        capabilities.setCapability("chrome.binary", chromeDriverPath);  
        capabilities.setCapability(ChromeOptions.CAPABILITY, options);  
		driver = new ChromeDriver();
		driver.manage().window().maximize();
//		maximise(driver);
		driver.manage().timeouts().pageLoadTimeout(60, TimeUnit.SECONDS);
		return driver;
	}
    
	/**
	 * remote方式打开chrome浏览器
	 * @param nodeUrl 远程连接地址
	 * @return webdriver
	 * @throws MalformedURLException
	 */
	public static WebDriver getRemoteChromeDriver(String nodeUrl) throws MalformedURLException {
		DesiredCapabilities dc = DesiredCapabilities.chrome(); // 设置需要驱动的浏览器，其他的浏览器都是以此类推
		driver = new RemoteWebDriver(new URL("http://localhost:4444/wd/hub"), dc);
		// 这个URL：localhost是要remote PC 的IPAddress，需要改为你自己的
		driver.manage().window().maximize();
//		maximise(driver);
		driver.manage().timeouts().pageLoadTimeout(60, TimeUnit.SECONDS); // 设置页面加载超时的最大时长
		return driver;
	}
	
	/**
	 * 浏览器强制最大化
	 * @param driver WebDriver
	 */
    public static void maximise(WebDriver driver) { 
    	try{
    		driver.manage().window().maximize();
    	}catch (WebDriverException e) {
    		e.printStackTrace();
    	}   	
    	int width = driver.manage().window().getSize().getWidth();
    	int height = driver.manage().window().getSize().getHeight();
	    java.awt.Dimension  screenDims = Toolkit.getDefaultToolkit().getScreenSize();  
        int screenwidth = (int) screenDims.getWidth();  
        int screenheight = (int) screenDims.getHeight();
        Boolean ismaxi = false;
    	for (int i = 1; i <= 60; i++) {
    		if (Math.abs(screenwidth - width) > 100 && Math.abs(screenheight - height) > 100) {
    			driver.manage().window().maximize();
    			try {
					Thread.sleep(1000);
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
    		}
    		else {
    			ismaxi = true;
    			break;
    		}
    	}
    	if (!ismaxi) {
    		log.info("浏览器最大化失败：width:"+width+"height:"+height+"即将强制最大化");
    	    final JavascriptExecutor js = (JavascriptExecutor) driver;
    	    js.executeScript("window.open('','testwindow','width=400,height=200')");
    	    driver.close();
    	    driver.switchTo().window("testwindow");
    	    js.executeScript("window.moveTo(0,0);");
    	    js.executeScript("window.resizeTo("+screenwidth+","+screenheight+");");
    	    log.info("强制最大化成功");
    	}
    } 
    /**
     * 给driver注册WebDriverEventListener监听器
     * @param we WebDriverEventListener
     * @param wd WebDriver
     * @return WebDriver
     */
    public static WebDriver registerEventListener (WebDriverEventListener we, WebDriver wd) {
    	return new EventFiringWebDriver(wd).register(we);
    }
}
